package com.timemachine.springcloud.controller;

import com.timemachine.springcloud.entity.User;
import com.timemachine.springcloud.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * UserController
 * Restful API
 * @author Liuguanglei tonytimemachine@gmail.com
 * @create 2017-06-下午11:24
 */

@Api(value = "API - UserController", description = "用户接口详情")
@RestController
public class UserController {



    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private DiscoveryClient discoveryClient;



    @Autowired
    private UserService userService;


    @ApiOperation(value="获取用户列表", notes="")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 请求已完成"),
            @ApiResponse(code = 400, message = "请求中有语法问题，或不能满足请求"),
            @ApiResponse(code = 401, message = "未授权客户机访问数据"),
            @ApiResponse(code = 404, message = "服务器找不到给定的资源；文档不存在"),
            @ApiResponse(code = 500, message = "服务器不能完成请求")}
    )
    @GetMapping(value = "/list")
   public List<User> list(){

        ServiceInstance instance=discoveryClient.getLocalServiceInstance();
        LOGGER.info("call user/list service  host is  "+instance.getHost()+"service_id is "+instance.getServiceId());
        return userService.getAllUser();
   }

   @ApiOperation(value = "登录系统")
   @GetMapping(value = "/login")
   public User login( @RequestParam String name,@RequestParam String password){

       User user=userService.login(name,password);
       return user;
   }

   @ApiOperation(value = "注册系统")
   @PostMapping("/register")
   public String register(@ModelAttribute User user){
       User result =userService.register(user);
       return result!=null?"success":"fail";
   }

   @ApiOperation(value = "获取指定ID的用户信息")
   @ApiParam(name = "id",allowableValues = "")
   @GetMapping("/get/{id}")
   public User get(@PathVariable Long id){

       return userService.getUserById(id);
   }

   @PutMapping("/update/{id}")
   public String update(@PathVariable Long id,@ModelAttribute User user){

       User updatedUser =userService.getUserById(id);
       updatedUser.setName(user.getName());
       updatedUser.setPassword(user.getPassword());
       updatedUser.setCreateDate(new Date());
       User result= userService.register(updatedUser);
       return result!=null?"success":"fail";

   }


   @DeleteMapping("/delete/{id}")
   public String delete(@PathVariable Long id){

       User user =new User();
       user.setId(id);
       userService.writeOff(user);

       return "success";
   }


}
